package com.emily.test.controller;

import com.alibaba.fastjson.JSONObject;
import com.emily.test.constant.ReturnValueConstants;
import com.emily.test.controller.result.ResponseResult;
import com.emily.test.model.OContact;
import com.emily.test.model.OInformation;
import com.emily.test.service.OInformationService;
import com.emily.test.service.RedisService;
import com.emily.test.utils.ConstentUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "OInformationController")
@Api(value = "oInformationApi", description = "oInformation接口类", position = 1, produces = MediaType.APPLICATION_JSON_VALUE)
public class OInformationController {
    private Logger logger = LoggerFactory.getLogger(OInformationController.class);

    @Autowired
    private OInformationService oInformationService;

    @Autowired
    private RedisService redisService;

    /**
     * 根据条件查询简介信息列表
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @ApiOperation(value="根据条件查询简介信息列表", notes="根据条件查询简介信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID"),
            @ApiImplicitParam(name = "info", value = "简介"),
            @ApiImplicitParam(name = "companyCode", value = "公司code"),
            @ApiImplicitParam(name = "img", value = "简介图片")
    })
    @PostMapping(value = "selectInformationByCondition")
    public ResponseResult selectInformationByCondition(@RequestBody(required = false) JSONObject jsonObject, HttpServletRequest request) throws Exception {
        OInformation oInformation= (OInformation) ConstentUtil.json2Object(jsonObject, OInformation.class);
        String token = request.getHeader("token");
        Map<String,Object> userMap= (Map<String, Object>) redisService.get(token);
        String companyCode=null;
        if(!ConstentUtil.isEmpty(jsonObject)){
            if(!ConstentUtil.isEmpty(jsonObject.getString("companyCode"))){
                companyCode=jsonObject.getString("companyCode");
            }
        }
        if(!ConstentUtil.isEmpty(userMap)){
            if(!ConstentUtil.isEmpty(userMap.get("companyCode"))){
                companyCode= userMap.get("companyCode") == null ? null : (String) userMap.get("companyCode");
            }
        }
//        String companyCode= userMap.get("companyCode") == null ? null : (String)userMap.get("companyCode");
        oInformation.setCompanyCode(companyCode);
        try {
            List<OInformation> oInformationList=oInformationService.selectInformationByCondition(oInformation);
            logger.info("根据条件查询简介信息列表成功:{}",oInformationList);
            return ResponseResult.success(oInformationList);
        } catch (Exception e) {
            logger.info("根据条件查询简介信息异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }

    /**
     * 插入一条简介
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @ApiOperation(value="插入一条简介", notes="插入一条简介")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID"),
            @ApiImplicitParam(name = "info", value = "简介内容"),
            @ApiImplicitParam(name = "companyCode", value = "公司code"),
            @ApiImplicitParam(name = "img", value = "图片")
    })
    @PostMapping(value = "insertInformation")
    public ResponseResult insertInformation(@RequestBody JSONObject jsonObject,HttpServletRequest request) throws Exception {
        OInformation oInformation= (OInformation) ConstentUtil.json2Object(jsonObject,OInformation.class);
        String token = request.getHeader("token");
        Map<String,Object> userMap= (Map<String, Object>) redisService.get(token);
        String companyCode= userMap.get("companyCode") == null ? null : (String)userMap.get("companyCode");
        oInformation.setCompanyCode(companyCode);
        OInformation of=new OInformation();
        of.setCompanyCode(companyCode);

        try {
            //如果表中含有该公司简介的数据，则对其进行修改
            List<OInformation> ofList=oInformationService.selectInformationByCondition(of);
            if(!ConstentUtil.isEmpty(ofList)){
                of.setId(ofList.get(0).getId());
                of.setCompanyCulture(oInformation.getCompanyCulture());
                of.setImg(oInformation.getImg());
                of.setInfo(oInformation.getInfo());
                int nu= oInformationService.updateInformationById(of);
                logger.info(ReturnValueConstants.UPDATE_SUCCESS);
                return ResponseResult.success(nu);
            }
            int num =oInformationService.insertInformation(oInformation);
            logger.info("插入一条简介成功,插入条数:{}",num);
            return ResponseResult.success(num);
        } catch (Exception e) {
            logger.info("插入一条简介异常",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
        }
    }

    /**
     * 修改简介信息
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @ApiOperation(value="修改简介信息", notes="修改简介信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID",required = true),
            @ApiImplicitParam(name = "info", value = "简介内容"),
            @ApiImplicitParam(name = "companyCode", value = "公司code"),
            @ApiImplicitParam(name = "img", value = "简介图片")
    })
    @PostMapping(value = "updateInformation")
    public ResponseResult updateInformation(@RequestBody JSONObject jsonObject) throws Exception {
        OInformation oInformation= (OInformation) ConstentUtil.json2Object(jsonObject,OInformation.class);
        if(ConstentUtil.isEmpty(oInformation)){
            return ResponseResult.fail("修改的信息"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        if(ConstentUtil.isEmpty(oInformation.getId())){
            return ResponseResult.fail("简介ID"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        try {
            int num =oInformationService.updateInformationById(oInformation);
            logger.info("修改简介成功,修改条数:{}",num);
            return ResponseResult.success(num);
        } catch (Exception e) {
            logger.info("修改简介异常",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.UPDATE_FAILURE);
        }
    }

    /**
     * 删除多条简介
     * @param jsonObject    其中ids的格式为:ids={1,2,3,4}
     * @return
     */
    @ApiOperation(value="删除多条简介", notes="删除多条简介")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ids", required = true)
    })
    @PostMapping(value = "deleteInformationByIds")
    public ResponseResult deleteInformationByIds(@RequestBody JSONObject jsonObject){
        String ids=jsonObject.getString("ids").replaceAll("\\[","").replaceAll("]","");
        String[] idStr=ids.split(",");
        List<OInformation> oInformationList=new ArrayList<OInformation>();
        if(idStr.length !=0){
            for( int i=0;i<idStr.length;i++){
                OInformation oInformation=new OInformation();
                oInformation.setId(ConstentUtil.strToInteger(idStr[i]));
                oInformationList.add(oInformation);
            }
        }
        try {
            int num=oInformationService.deleteInformationByIds(oInformationList);
            logger.info("ids为{}的信息已删除",ids);
            return ResponseResult.success(oInformationList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.DELATE_FAILURE);
        }
    }
}
